const PERSIST_INIT = 'PERSIST_INIT';

export default function persistReducer(persistConfig,reducers){
  const key = `persist:${persistConfig.key}`;
  let isInited = false;
  return function(state,action){
    switch (action.type) {
    case PERSIST_INIT:
      isInited = true;
      const value = persistConfig.storage.get(key);
      state = JSON.parse(value);
      return state;
    default:
      if(isInited){
        state = reducers(state, action);
        persistConfig.storage.set(key, JSON.stringify(state));
        return state;

      }else{
        //仓库初始化时会派发一个默认动作，此时还没有一个组件开始加载，so自然PersistGate也还没加载，PERSIST-INIT 动作自然也还没有派发
        //此时我们是不需要写入storage的，如果写入了实际上会以初始的state覆盖原本已经写入的storage
        return reducers(state, action);
      }

    }
  }
}
